/**
 * 获取喜马拉雅 资源
 */

import * as R from "request";
import * as cheerio from "cheerio";
import * as fs from "fs";
let url:string = 'http://www.ximalaya.com/13609695/album/2868786';
let sound_ids = [];
function getSoundIds(url:string):Promise<string[]>{
    return new Promise(function(resolve, reject){
        R.get(url, function(error, res, data){
            if (error) {
                reject(error);
            } else {
                let $ = cheerio.load(data);
                let sound_ids = $('.personal_body').attr('sound_ids').split(',');
                resolve(sound_ids);
            }
        });
    });
}


let dir = './audio/';

// 下载数据
function download(id:number){
    let baseUrl = "http://www.ximalaya.com/tracks/"+id+'.json';
    return new Promise((resolve, reject) => {
        R.get(baseUrl, function(error, res, data){
            if(error) {
                reject(error);
            }
            data = JSON.parse(data);
            const path = data.play_path_64;
            const title = data.title;
            console.log("正在下载 <<"+title+">>");
            R.get(path, {
                headers : {
                    "Content-type": "application/octet-stream"
                }
            })
            .pipe(fs.createWriteStream(dir+title+".m4a")
            .on('close', () =>  resolve(title + " 下载完成")))
    
        })
    });
}


async function run(){
    let sound_ids = await getSoundIds(url);
    for await (let id in sound_ids) {
        let log = await download(sound_ids[id]);
        console.log(log);
    }
}

run();

